const express = require('express');
const router = express.Router();
const Repair = require('../models/Repair');
const multer = require('multer');
const fs = require('fs');

// 设置multer存储策略
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/'); // 指定文件保存的路径
  },
  filename: function (req, file, cb) {
    cb(null, `${Date.now()}-${file.originalname}`); // 使用时间戳来命名文件，避免文件名冲突
  }
});

// 创建multer实例
const upload = multer({ storage: storage });


router.get('/repairs', async (req, res) => {
  try {
    const repairs = await Repair.find({});
    res.render('repairs/index', { repairs });
  } catch (err) {
    console.error(err);
    res.status(500).send('Internal Server Error');
  }
});

router.get('/repairs/new', (req, res) => {
  res.render('repairs/new');
});

// 使用 upload.single('images') 中间件处理最多9个文件上传
router.post('/repairs', upload.array('images',9), async (req, res) => {
  const { title, description,} = req.body;
  imagesPath=[];
  if(req.files){    
    req.files.forEach(
      file=>{
        imagesPath.push( file.filename);        
      })
  }
  // 读取上传的图片文件并转换为 base64 格式
  //const imageData = fs.readFileSync(req.file.path);
  //const base64Image = Buffer.from(imageData).toString('base64');

  // 存储 base64Image 到数据库中的 repair.images 字段中
  const repair = new Repair({
    title,
    description,
    status: 'pending',
    created_at: new Date(),
    images: imagesPath
  });
  
  await repair.save();
  res.redirect('/repairs');
});

module.exports = router;

